#!/usr/bin/env node

import { execSync, spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import AdmZip from 'adm-zip';

// 定义需要构建的目标平台和架构
const targets = [
  { platform: 'win', arch: 'x64', nodeTarget: 'node18-win-x64' },
  { platform: 'linux', arch: 'x64', nodeTarget: 'node18-linux-x64' },
  { platform: 'macos', arch: 'x64', nodeTarget: 'node18-macos-x64' }
];
const outputDir = path.join(process.cwd(), 'build');
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

console.log('开始构建 Tmake 可执行文件...');
console.log('执行 TypeScript 编译...');
try {
  execSync('npm run build', { stdio: 'inherit' });
  console.log('TypeScript 编译成功!');
} catch (error) {
  console.error('TypeScript 编译失败:', error);
  process.exit(1);
}
async function buildAllTargets() {
  for (const target of targets) {
    await buildTarget(target);
  }
}
async function buildTarget(target: { platform: string; arch: string; nodeTarget: string }) {
  const { platform, arch, nodeTarget } = target;
  const outputName = platform === 'win' ? 'tmake.exe' : 'tmake';
  const executablePath = path.join(outputDir, `${outputName}`);
  const zipFileName = `tmake-${platform}_${arch}.zip`;
  const zipFilePath = path.join(outputDir, zipFileName);

  console.log(`\n构建 ${platform}-${arch} 平台的可执行文件...`);
  
  try {
    execSync(
      `npx pkg --targets ${nodeTarget} dist/index.js -o ${executablePath} --ignore-scripts`,
      { stdio: 'inherit' }
    );
    console.log(`构建 ${platform}-${arch} 平台成功!`);
    console.log(`创建 ${zipFileName} 压缩包...`);
    const zip = new AdmZip();
    zip.addLocalFile(executablePath);
    const projectDir = path.join(process.cwd(), 'project');
    if (fs.existsSync(projectDir)) {
      zip.addLocalFolder(projectDir, 'project');
    } else {
      console.warn(`警告: project 目录不存在: ${projectDir}`);
    }
    zip.writeZip(zipFilePath);
    if (platform !== 'win') {
      try {
        execSync(`chmod +x ${executablePath}`);
      } catch (error) {
        console.warn(`无法设置执行权限: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
    
    console.log(`成功创建压缩包: ${zipFilePath}`);
    
  } catch (error) {
    console.error(`构建 ${platform}-${arch} 平台失败:`, error);
  }
}
async function main() {
  try {
    await buildAllTargets();
    console.log('\n所有构建任务完成!');
    console.log(`输出目录: ${outputDir}`);
  } catch (error) {
    console.error('构建过程中出现错误:', error);
    process.exit(1);
  }
}
function checkDependencies() {
  try {
    require.resolve('adm-zip');
    return true;
  } catch (error) {
    return false;
  }
}
function installDependencies() {
  if (!checkDependencies()) {
    console.log('安装所需依赖...');
    try {
      execSync('npm install adm-zip --save-dev', { stdio: 'inherit' });
      console.log('依赖安装成功!');
    } catch (error) {
      console.error('依赖安装失败:', error);
      process.exit(1);
    }
  }
}
installDependencies();
main();